<template>
  <div class="login">
    <van-nav-bar left-arrow @click-left="homeClick"></van-nav-bar>
    <div class="login-form">
      <h2 class="h2">短信登录</h2>
      <van-form ref="form">
        <van-field
          placeholder="请输入手机号"
          v-model="form.mobile"
          :rules="rules.mobile"
          name="mobile"
          autofocus
        ></van-field>
        <van-field
          placeholder="请输入验证码"
          v-model="form.code"
          :rules="rules.code"
        >
          <template #button>
            <div @click="verifyMobile">{{ verify }}</div>
          </template>
        </van-field>
        <van-button class="btn-form" @click="submit">登录</van-button>
      </van-form>
    </div>
  </div>
</template>
<script>
import { authorizations, smsCodes } from '@/api/user.js'
export default {
  name: 'login',
  data () {
    return {
      verify: '发送验证码',
      form: {
        mobile: '13979388695',
        code: '246810'
      },
      rules: {
        mobile: [
          {
            required: true,
            message: '',
            trigger: 'onBlur'
          },
          {
            validator: value => {
              const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              return reg.test(value)
            },
            message: '请正确输入手机号',
            trigger: 'onBlur'
          }
        ],
        code: [
          {
            required: true,
            message: '',
            trigger: 'onChange'
          },
          {
            validator: value => {
              const reg = /^\d{6}$/
              return reg.test(value)
            },
            message: '请输入六位验证码',
            trigger: 'onChange'
          }
        ]
      }
    }
  },
  methods: {
    homeClick () {
      this.$router.push('/')
    },
    verifyMobile () {
      this.$refs.form.validate('mobile').then(async () => {
        let num = 60
        const timeId = setInterval(() => {
          this.verify = --num + '秒后重新发送验证码'
          if (this.verify < 1) {
            this.verify = '重新发送验证码'
            clearInterval(timeId)
          }
        }, 1000)
        await smsCodes(this.form.mobile)
      })
    },
    submit () {
      this.$refs.form.validate().then(async () => {
        this.$toast.loading({ duration: 0 })
        const res = await authorizations(this.form)
        this.$store.commit('user/setStateToken', res.data.token)
        this.$toast.success('登录成功')
        this.$router.push('/')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.login {
  ::v-deep .van-nav-bar .van-icon {
    color: #999;
  }
  .login-form {
    padding: 0 20px;
    .h2 {
      padding: 20px 15px;
      font-weight: 400;
    }
  }
  .btn-form {
    width: 100%;
    color: #fff;
    background: linear-gradient(to right, #fe4f4f, #fc6528);
    margin-top: 30px;
  }
}
</style>
